package com.example.springboot.controller;

import cn.hutool.core.io.FileUtil;
import com.example.springboot.common.AuthAccess;
import com.example.springboot.common.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/file")
public class FileController {

    @Value("${ip:localhost}")
    String ip;

    @Value("${server.port}")
    String port;

    @AuthAccess
    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws IOException{
            String originalFilename = file.getOriginalFilename(); // 文件的原始名称

            String mainName = FileUtil.mainName(originalFilename);
            String extName = FileUtil.extName("文件的后缀");
            String projectPath = System.getProperty("user.dir"); // E:\Project\springboot
            String filesPath = projectPath + "\\files"; // 文件存储的目录
            File parentFile = new File(filesPath);
            if (!parentFile.exists()) {
                parentFile.mkdirs(); // 如果当前文件的父级目录不存在，就创建
            }
            File saveFile = new File(filesPath + File.separator + originalFilename);
            if (saveFile.exists()){
                originalFilename = System.currentTimeMillis() + "_" + mainName +"." +extName;
                saveFile = new File(filesPath + File.separator + originalFilename);
            }
            file.transferTo(saveFile);
            String url = "http://" + ip + ":" + port + "/file/download/" + originalFilename;
            return Result.success(url); // 返回文件的链接，这个链接就是文件的下载地址，这个下载地址就是后台提供的
    }

    @GetMapping("/download/{fileName}")
    public void download(@PathVariable String fileName, HttpServletResponse response) throws IOException {

        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(new byte[1024]); // 数组是一个字节数组，也就是文件的字节流数组
    }
}
